package com.monkeyboy.service.rocketmqordermsg;

import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author Gavin
 * @date 2020.08.23 12:54
 */
@Service
public class OrderMessageProducer {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void orderProductMessage() throws Exception {
        rocketMQTemplate.setMessageQueueSelector(new MessageQueueSelector() {
            @Override
            public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                //实际生产中可以传入订单号，根据订单号取模或者hash运算得到固定队列的下标
                int orderId = Integer.parseInt(o.toString());
                int index = orderId % 4;
                return list.get(1);
            }
        });
        rocketMQTemplate.setDefaultDestination("order_group");
        for (int i = 0; i < 20; i++) {
            rocketMQTemplate.syncSendOrderly("order_topic", "" + i, i + "");
        }
    }
}
